//
//  AttractMoneyViewController.m
//  ASHT_IOS
//
//  Created by 宋安安 on 14-4-8.
//  Copyright (c) 2014年 宋安安. All rights reserved.
//

#import "AttractMoneyViewController.h"
#import "AFAppDotNetAPIClient.h"
#import "NewsInfoEntity.h"
#import "WebContentViewController.h"
#import "MBProgressHUD.h"

#define degressToRadians(X) ( M_PI * (X) / 180 )
@interface AttractMoneyViewController ()

@end

@implementation AttractMoneyViewController

@synthesize tableDataArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _Adaptation = YES;
        isarler=YES;
    }
    return self;
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _currentPage = 1;
    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *egview =
        [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(
                                                                    0.0f,
                                                                    0.0f-attractMoneyTable.frame.size.height,
                                                                    attractMoneyTable.frame.size.width,
                                                                    attractMoneyTable.frame.size.height)];
        
		egview.delegate = self;
		[attractMoneyTable addSubview:egview];
        //        [self.view_Content addSubview:egview];
		_refreshHeaderView = egview;
        egview=nil;
		
	}

    [_refreshHeaderView refreshLastUpdatedDate];
    [self initScrollView];
    
    NSString *url=@"phone!getTplbList.action";
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
        NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
        NSArray *ary_success=[dic_result objectForKey:@"context"];
        
        carselTV =[[CarouselTableView alloc] initWithFrame:CGRectMake(0, 0, 160 , 320)];
        carselTV.transform=CGAffineTransformMakeRotation(degressToRadians(-90));
        carselTV.center=CGPointMake(160, 80);
        carselTV.arr_new=[NSMutableArray arrayWithArray:ary_success];
        
         carselTV.ctvdelegate=self;
        [view_Header addSubview:carselTV];
        pageControl.backgroundColor = [UIColor clearColor];
        pageControl.pageIndicatorTintColor=[UIColor grayColor];
        pageControl.currentPageIndicatorTintColor=[UIColor blackColor];
        pageControl.numberOfPages = ary_success.count;
        pageControl.currentPage = 0;
        for (int i=0; i<pageControl.subviews.count; i++) {
            UIImageView* dot = [pageControl.subviews objectAtIndex:i];
            CGSize size;
            size.height = 4;     //自定义圆点的大小
            size.width = 4;      //自定义圆点的大小
            [dot setFrame:CGRectMake(dot.frame.origin.x, dot.frame.origin.y, size.width, size.width)];
        }

        [view_Header addSubview:pageControl];
        _Load=NO;
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        if (isarler) {
            NSString *message=[self ErrorMessageHandling:error];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:message
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
            [alert show];
            alert=nil;
            isarler=NO;
        }
        _Load=YES;
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];

    attractMoneyTable.tableHeaderView=view_Header;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    isarler=YES;
    
}

-(IBAction)pageChange:(id)sender;
{
    [carselTV setContentOffset:CGPointMake(0,pageControl.currentPage * 320) animated:YES];
    [pageControl setCurrentPage:pageControl.currentPage];
}
-(void)ScrollCarouselTableViewDelegate:(int) page
{
    [pageControl setCurrentPage:page];
    [pageControl updateCurrentPageDisplay];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        if (_Adaptation) {
            self.view_Content.frame=CGRectMake(self.view_Content.frame.origin.x,self.view_Content.frame.origin.y,self.view_Content.frame.size.width,self.view_Content.frame.size.height-20);
            _Adaptation=NO;
        }
        
    }
    if (_Load) {
        [self initScrollView];
        
        NSString *url=@"phone!getTplbList.action";
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
            NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
            NSArray *ary_success=[dic_result objectForKey:@"context"];
            
            carselTV =[[CarouselTableView alloc] initWithFrame:CGRectMake(0, 0, 160 , 320)];
            carselTV.transform=CGAffineTransformMakeRotation(degressToRadians(-90));
            carselTV.center=CGPointMake(160, 80);
            carselTV.arr_new=[NSMutableArray arrayWithArray:ary_success];
            
            carselTV.ctvdelegate=self;
            [view_Header addSubview:carselTV];
            pageControl.backgroundColor = [UIColor clearColor];
            pageControl.pageIndicatorTintColor=[UIColor grayColor];
            pageControl.currentPageIndicatorTintColor=[UIColor blackColor];
            pageControl.numberOfPages = ary_success.count;
            pageControl.currentPage = 0;
            
            [view_Header addSubview:pageControl];
            _Load=NO;
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
            if (isarler) {
                NSString *message=[self ErrorMessageHandling:error];
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                              message:message
                                                             delegate:nil
                                                    cancelButtonTitle:@"确定"
                                                    otherButtonTitles:nil];
                [alert show];
                alert=nil;
                isarler=NO;
            }
            _Load=YES;
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        }];
        
        attractMoneyTable.tableHeaderView=view_Header;
    }
}
-(IBAction)btn_FinancialLoanType_OnClick:(id)sender
{
    if (btn_Type==sender) {
        return;
    }
    if (btn_Type) {
        btn_Type.selected=NO;
    }
    btn_Type=(UIButton*)sender;
    btn_Type.selected=YES;
    NSLog(@"%@",btn_Type.titleLabel.text);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    return tableDataArray.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	//NSLog(@"====in 设置每行的数据=====分区＝%d 行＝%d",indexPath.section,indexPath.row);
	
    NSUInteger row = [indexPath row];
	static NSString *CellIdentifier = @"Cell";
	
	DetailedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
	{
        NSArray *nibs=[[NSBundle mainBundle] loadNibNamed:@"DetailedCell" owner:self options:nil];
        if (nibs.count>0) {
            cell =[nibs objectAtIndex:0];
        }
        
    }
    
    
	//行是否允许点击事件
	tableView.allowsSelection=YES;
	NewsInfoEntity *entity = [self.tableDataArray objectAtIndex:row];
	//行是否允许点击事件
	tableView.allowsSelection=YES;
	//行选中的样式
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.lab_title.text = entity.title;
    cell.lab_content.text = entity.content;
    [cell imageUrl:entity.imageUrl];
    return cell;
}

//查看表格滚动的位置
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    int curRowCount = 0;
    curRowCount += (indexPath.row + 1);
    //NSLog(@"curRowCount = %d",curRowCount);
    if (curRowCount == _currentPage*5 - 1)
    {
        _currentPage++;
        //NSLog(@"page = %d",_currentPage);
        [self initDataSource:tableDataArray.count rowcount:5 categordId:parentId];
    }
}
//选中行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailedCell *cell = (DetailedCell *)[tableView cellForRowAtIndexPath:indexPath];
    [self selectCell:cell];
    detailedcell=cell;
    NSUInteger row = [indexPath row];
  
    WebContentViewController *webVC = [[WebContentViewController alloc] initWithNibName:XIB_Version(@"WebContentViewController") bundle:nil];
    NewsInfoEntity *newEntity = [tableDataArray objectAtIndex:row];
    webVC.key=newEntity.title;
    webVC.titleStr = self.label_title.text;
    NSString *requestStr=[NSString stringWithFormat:SERVER_BASICE_URL@"phone!getArticle.action?articleId=%@",newEntity.articleId];
    webVC.requestStr = requestStr;
    [self.app.viewDeckController.navigationController pushViewController:webVC animated:YES];
    
}
-(void)selectCell:(DetailedCell *) cell
{
    if (detailedcell==cell) {
        return;
    }
    [detailedcell.image_back setHighlightedImage:cell.image_back.highlightedImage];
    [detailedcell.image_back setImage:cell.image_back.image];
    UIImage *image_h=cell.image_back.highlightedImage;
    [cell.image_back setHighlightedImage:cell.image_back.image];
    [cell.image_back setImage:image_h];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}

-(void) initScrollView
{
    NSString *url=@"phone!getZsyzCategoryList.action";
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
        NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
        NSArray *arr_success=[dic_result objectForKey:@"context"];
        
        for (int i = 0; i<arr_success.count; i++) {
            NSDictionary *item = [arr_success objectAtIndex:i];
            UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
            btn.tag=[[item objectForKey:@"categoryId"] integerValue];
            
            NSString *titleName = [item objectForKey:@"categoryName"];
            if (titleName.length > 5) {
                int i=titleName.length;
                i=i-4;
                titleName = [titleName substringFromIndex:i];
            }
            NSString *title=[NSString stringWithFormat:@"%@",titleName];
            
            [btn setTitle:title forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn.frame=CGRectMake(i*(80+10), 0, 80, 30);
            [btn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"back_cell.png"] forState:UIControlStateSelected];
            
            [btn addTarget:self action:@selector(initTableView:) forControlEvents:UIControlEventTouchUpInside];
            if (i==0) {
                [self initTableView:btn];
            }
            [scroll_view addSubview:btn];
            scroll_view.showsVerticalScrollIndicator=NO;
            scroll_view.contentSize=CGSizeMake(btn.frame.origin.x+btn.frame.size.width, 0);
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        if (isarler) {
            NSString *message=[self ErrorMessageHandling:error];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:message
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
            [alert show];
            alert=nil;
            isarler=NO;
        }

        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
}

-(void) initTableView:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if (btn_Type==sender) {
        return;
    }
    if (btn_Type) {
        btn_Type.selected=NO;
    }
    btn_Type=(UIButton*)sender;
    btn_Type.selected=YES;
    parentId = btn.tag;
    [self initDataSource:0 rowcount:5 categordId:parentId];
}

-(void)initDataSource :(int)startnum rowcount:(int)rowcount categordId:(int)categordId
{
    
    NSString *url=[NSString stringWithFormat:@"phone!getArticleList.action?categoryId=%i&startnum=%i&rowcount=%i",parentId,0,5];
    tableDataArray = [[NSMutableArray alloc] init];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
        NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
        NSArray *arr_success=[dic_result objectForKey:@"context"];
        
        for (int i = 0; i<arr_success.count; i++) {
            NSDictionary *item = [arr_success objectAtIndex:i];
            NewsInfoEntity *entity = [[NewsInfoEntity alloc] init];
            
            entity.articleId = [item objectForKey:@"articleId"];
            entity.title = [item objectForKey:@"title"];
            entity.imageUrl = [item objectForKey:@"imageUrl"];
            entity.content = [item objectForKey:@"content"];
            [tableDataArray addObject:entity];
            entity = nil;
            
        }
        [attractMoneyTable reloadData];
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        if (isarler) {
            NSString *message=[self ErrorMessageHandling:error];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:message
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
            [alert show];
            alert=nil;
            isarler=NO;
        }

        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
    
}
- (void)reloadTableViewDataSource{
    
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    
}

- (void)ind_doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:attractMoneyTable];
	
}
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	//[delegate pullUpdateData];
    //	[self reloadTableViewDataSource];
    isarler=YES;
	[tableDataArray removeAllObjects];
    _currentPage = 1;
    [self initDataSource:0 rowcount:5 categordId:parentId];
    //    newsLong=YES;
    [self performSelector:@selector(ind_doneLoadingTableViewData) withObject:nil afterDelay:0];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
    
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

- (void)egoRefreshTableHeaderDidTriggerToBottom
{

}


@end
